package tw.cating.karmasaver.rss;

import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import tw.cating.Utility.ADUtility;
import tw.cating.karmasaver.Constants;
import tw.cating.karmasaver.R;
import tw.cating.karmasaver.intef.finishListener;
import tw.cating.karmasaver.intef.finishListenerEx;
import tw.cating.karmasaver.intef.selectedChangeListener;
import tw.cating.karmasaver.plurk.plurkApi;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class EditRssActivity extends Activity implements selectedChangeListener{

	Context mContext = null;
	rssSiteAdapter mAdapter = null;
	rssHandler mHandler = null;
	ListView mListView = null;
	private int checkedCount = 0;
	Button btn_finish = null;
	Button btn_checknew = null;
	Thread mADThread = null;
	plurkApi plurk = null;
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.main);
		mAdapter = new rssSiteAdapter(this);
		mAdapter.setSelectedChangeListener(this);
		mListView = (ListView)findViewById(R.id.rsslist);
		mListView.setAdapter(mAdapter);
		btn_finish = (Button)findViewById(R.id.btn_editrss);
		btn_finish.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (checkedCount != 0) {
					mAdapter.deleteCheckedItem();
				} else {
					finish();
				}
			}
		});
		
		btn_checknew = (Button)findViewById(R.id.btn_checknew);
		btn_checknew.setText(R.string.checkrss);
		btn_checknew.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (plurk == null) {
					plurk = new plurkApi(mContext);
				}
				
				if (plurk.isLogined()) {
					mMsgHandler.sendEmptyMessage(EditRssActivity.MSG_PREPARELOGININFOSUCCESSED);
				} else {
					prepareLogin();
				}
				
				showDialog(0);
			}
		});
		setFinishButton();
		WebView adView = (WebView)findViewById(R.id.ad_view);
		mADThread = ADUtility.prepareADWebView(this, adView); 
	}
	
    @Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		if (mADThread != null && mADThread.isAlive()) {
			mADThread.interrupt();
		}
		mAdapter.commitSite();
	}

	@Override
    protected Dialog onCreateDialog(int id) {
        final ProgressDialog dialog = new ProgressDialog(this);
       	dialog.setMessage(mContext.getResources().getString(R.string.rss_check_checking));
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        return dialog;
    }
	
	public void setFinishButton() {
		if (checkedCount > 0) {
			btn_finish.setText(R.string.rss_check_delete);
		} else {
			btn_finish.setText(R.string.rss_check_finish);
		}
	}

	public void onChanged() {
		// TODO Auto-generated method stub
		checkedCount = 0;
		for (int i = 0; i < mAdapter.getCount(); i++) {
			rssSiteAdapter.rssSite site = (rssSiteAdapter.rssSite)mAdapter.getItem(i);
			if (site.isChecked) {
				checkedCount++;
			}		
		}
		
		setFinishButton();
	}
	
	public static final int MSG_ABORT = -1;
	public static final int MSG_PREPARELOGININFOSUCCESSED = 1;
	public static final int MSG_LOGINED = 2;
	public static final int MSG_GETPLURKSUCCESSED = 3;
	public static final int MSG_FINISH = 4;
	Handler mMsgHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case MSG_PREPARELOGININFOSUCCESSED:
				LoginInfoReady();
				break;
			case MSG_LOGINED:
				getLastPlurk();
				break;
			case MSG_GETPLURKSUCCESSED:
				getPlurkResponse();
				break;
			case MSG_ABORT:
				dismissDialog(0);
//				Toast.makeText(mContext, error_msg, Toast.LENGTH_LONG)
//				.show();
				final AlertDialog mDialog = new AlertDialog.Builder(EditRssActivity.this)
				.setTitle("Error")
				.setMessage(error_msg)
				.show();
				break;
			case MSG_FINISH:
				dismissDialog(0);
				mAdapter.notifyDataSetChanged();
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	protected String error_msg = "";
	protected String mUsername = "";
	protected String mPassword = "";
	
	protected int plurk_id = 0;
	
	protected void getPlurkResponse() {
		plurk.getResponse(plurk_id, new finishListenerEx(){

			public void onFinish(String result) {
				// TODO Auto-generated method stub
				error_msg = mContext.getResources().getString(R.string.rss_check_wrongresponse);
				if (result == null) {
					mMsgHandler.sendEmptyMessage(MSG_ABORT);
				} else {
					try {
						JSONObject obj = new JSONObject(result);
						if (obj.has("responses")) {
							JSONArray responses = obj.getJSONArray("responses");
							for (int i = 0; i < responses.length(); i++) {
								JSONObject resp = responses.getJSONObject(i);
								if (resp.has("content_raw")) {
									mAdapter.add(resp.getString("content_raw"));
								}
							}
						}
						mMsgHandler.sendEmptyMessage(MSG_FINISH);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						mMsgHandler.sendEmptyMessage(MSG_ABORT);
						e.printStackTrace();
					}	
				}
			}
			
		});
	}
	
	protected void getLastPlurk() {
		plurk.checkRssNode(new finishListenerEx() {

			public void onFinish(String result) {
				// TODO Auto-generated method stub
				error_msg = mContext.getResources().getString(R.string.rss_check_hint);
				if (result == null) {
					mMsgHandler.sendEmptyMessage(MSG_ABORT);
				} else {
					try {
						boolean bSuccessed = false;
						JSONObject obj = new JSONObject(result);
						if (obj.has("plurks")) {
							JSONArray plurks = obj.getJSONArray("plurks");
							if (plurks.length() > 0) {
								JSONObject plurkObj = plurks.getJSONObject(0);
								if (plurkObj.has("content_raw") && plurkObj.getString("content_raw").equalsIgnoreCase("karmasaver")) {
									if (plurkObj.has("response_count") && plurkObj.getInt("response_count") > 0) {
										plurk_id = plurkObj.getInt("plurk_id");
										bSuccessed = true;
									} 
								}
							}
						}
						mMsgHandler.sendEmptyMessage(bSuccessed ? MSG_GETPLURKSUCCESSED : MSG_ABORT);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						mMsgHandler.sendEmptyMessage(MSG_ABORT);
						e.printStackTrace();
					}	
				}
			}
			
		});
	}
	
	Thread mAuthThread = null;
	protected void LoginInfoReady() {
		mAuthThread = plurk.requestLogin(mUsername, mPassword, new finishListener() {

			public void onFinish(int result) {
				// TODO Auto-generated method stub
				error_msg = "Login to Plurk Failed";
				if (result != plurkApi.LOGINRESULT_SUCCESSED) {
					mMsgHandler.sendEmptyMessage(MSG_ABORT);
				} else {
					mMsgHandler.sendEmptyMessage(MSG_LOGINED);
				}
			}
        	
        });	
	}
	
	protected void prepareLogin() {
		final AccountManager am = AccountManager.get(this);
        final Account[] accs = am.getAccountsByType(Constants.ACCOUNT_TYPE);
        
        error_msg = mContext.getResources().getString(R.string.rss_check_auth_fail);
        if (accs.length == 0) {
        	AccountManagerFuture<Bundle> addAccount =
        		am.addAccount(Constants.ACCOUNT_TYPE, Constants.AUTHTOKEN_TYPE, null, null, this, null, null);
        	try {
				Intent result = (Intent) addAccount.getResult().get(AccountManager.KEY_INTENT);
				startActivityForResult(result, 0);
			} catch (OperationCanceledException e) {
				// TODO Auto-generated catch block
				mMsgHandler.sendEmptyMessage(MSG_ABORT);
				e.printStackTrace();
			} catch (AuthenticatorException e) {
				// TODO Auto-generated catch block
				mMsgHandler.sendEmptyMessage(MSG_ABORT);
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				mMsgHandler.sendEmptyMessage(MSG_ABORT);
				e.printStackTrace();
			}
        	
        } else {
    		final Runnable run = new Runnable() {

    			public void run() {
    				// TODO Auto-generated method stub
    	        	Account acc = accs[0];
    	        	mUsername = acc.name;
    	        	AccountManagerFuture<Bundle> accountManagerFuture
    	            = am.getAuthToken(acc, Constants.AUTHTOKEN_TYPE, null, (Activity)mContext, null, null);
    	        	try {
    					Bundle authTokenBundle = accountManagerFuture.getResult();
    					mPassword = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
    					mMsgHandler.sendEmptyMessage(MSG_PREPARELOGININFOSUCCESSED);
    				} catch (OperationCanceledException e) {
    					// TODO Auto-generated catch block
    					mMsgHandler.sendEmptyMessage(MSG_ABORT);
    					e.printStackTrace();
    				} catch (AuthenticatorException e) {
    					// TODO Auto-generated catch block
    					mMsgHandler.sendEmptyMessage(MSG_ABORT);
    					e.printStackTrace();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					mMsgHandler.sendEmptyMessage(MSG_ABORT);
    					e.printStackTrace();
    				}				
    			}
    			
    		};
    		
            final Thread t = new Thread() {
                @Override
                public void run() {
                    try {
                        run.run();
                    } finally {

                    }
                }
            };
            t.start();
        }
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	        finish();
	    }
	    return super.onKeyDown(keyCode, event);
	}
}
